package com.android.readcard.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Tools for handler picture
 *
 * @author Ryan.Tang
 */
public final class ImageTools {

    /**
     * 图片转化为字节数组
     *
     * @return
     */
    public static byte[] bitmapToBytes(Bitmap bm) {
        byte[] bytes = null;
        if (bm != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
            bytes = baos.toByteArray();
        }
        return bytes;
    }

    /**
     * 保存图片到SD卡
     *
     * @param photoBitmap
     * @param photoName
     * @param path
     */
    public static File savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) {
        File parentFile = new File(path);
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        File file = new File(path + photoName);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 删除该路径下的所有图片
     */
    public static void deleteAllPhoto(final Activity activity, final String path) {
        Log.e("项目异常", "------删除文件--path----" + path);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File dir = new File(path);
                    if (dir == null || !dir.exists() || !dir.isDirectory()) {
                        return;
                    }
                    File[] files = dir.listFiles();
                    if (files.length > 0) {
                        for (File file : files) {
                            if (file.isFile()) {
                                Log.e("项目异常", path + "------删除文件--length----" + files.length);
                                file.delete();
//                                updateFileFromDatabase(activity, file);
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e("项目异常", "------删除文件--Exception----" + e.toString());
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
